import React, { useState, useEffect, useCallback } from 'react';
import store from '../../../../store';
import { JSONObject } from '../../../schema/common';
import {
  Button,
  Form,
  Input,
  Table,
  Space,
  Tree,
  Modal,
  DatePicker,
  Radio,
  Upload,
  message,
} from 'antd';
import { PlusOutlined, DeleteOutlined, FormOutlined } from '@ant-design/icons';
import { ColumnsType } from 'antd/lib/table';
import FileDownload from '../components/FileDownload';
import { flatTryCatch } from '../../../../servers/http';
import { industryIpaApi, jsonDoEncrypt } from 'admin/servers/servers';
import { debounce } from 'lodash';
import { invariableCol, fileContent } from './constant';
import moment from 'moment';
import './index.scss';

const { TextArea } = Input;
const timeFormat = 'YYYY-MM-DD';

const AddressBook: React.FC = () => {
  /**树相关 */
  const [treeData, setTreeData] = useState([
    { name: '全部', key: 'root', id: 'root', children: [] },
  ]);

  // 新增编辑树
  const [treeModalVisible, setTreeModalVisible] = useState(false);
  const [formTree] = Form.useForm();
  const [currentGroupId, setCurrentGroupId] = useState<string>(); // 选中的树节点id
  const [readyEditTree, setReadyEditTree] = useState<string>(); // 待编辑的树节点id

  const showTreeModal = (record = null) => {
    setTreeModalVisible(true);
    if (record) {
      formTree.setFieldsValue(record);
    } else {
      formTree.resetFields();
    }
  };

  const handleTreeModalOk = () => {
    formTree
      .validateFields()
      .then(async values => {
        const params = {
          parentId: currentGroupId,
          name: values.name,
          id: readyEditTree,
        };
        const { response, error } = await flatTryCatch(industryIpaApi.createGroup(params));
        if (error) return;
        if (response.code === 0) {
          fetchGroupTree();
        }
        setTreeModalVisible(false);
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  const handleTreeModalCancel = () => {
    setTreeModalVisible(false);
  };

  const handleAddTree = () => {
    setReadyEditTree(undefined);
    showTreeModal();
  };

  // 树结构交互
  const handleEditTree = (e, node) => {
    e.stopPropagation();
    e.preventDefault();
    const { name, id } = node;
    setReadyEditTree(id);
    showTreeModal({ name });
  };

  const handleDeleteTree = (e, node) => {
    e.stopPropagation();
    e.preventDefault();
    const { name, id } = node;

    Modal.confirm({
      title: '删除通讯录分组',
      icon: <DeleteOutlined />,
      content: `确定删除【${name}】通讯录分组吗, 是否继续?`,
      async onOk() {
        const { response, error } = await flatTryCatch(industryIpaApi.deleteGroup({ id }));
        if (error) return;
        if (response.code === 0) {
          message.success('删除成功');
          fetchGroupTree();
        } else {
          message.error('删除失败');
        }
      },
      onCancel() {},
    });
  };

  const renderTitle = node => {
    return (
      <div className="tree-node">
        <span>{node.name}</span>
        {node.key !== 'root' && (
          <div className="node-handle">
            <FormOutlined onClick={e => handleEditTree(e, node)} />
            <DeleteOutlined className="node-delete" onClick={e => handleDeleteTree(e, node)} />
          </div>
        )}
      </div>
    );
  };

  // 树点击
  const handleSelectTree = (selectedKeys: string[]) => {
    const pitchGroupId = selectedKeys[0] === 'root' ? undefined : selectedKeys[0];
    setCurrentGroupId(pitchGroupId);
    fetchDataList(
      { groupId: pitchGroupId, ...formSearch.getFieldsValue() },
      pagination.current,
      pagination.pageSize
    );
  };

  // 获取树
  const fetchGroupTree = useCallback(async () => {
    const { response, error } = await flatTryCatch(industryIpaApi.readGroupTree());
    if (error) return;
    const rootNode = { name: '全部', key: 'root', id: 'root', children: [] };
    rootNode.children = response.data ?? [];
    setTreeData([rootNode]);
  }, []);

  useEffect(() => {
    fetchGroupTree();
  }, [fetchGroupTree]);

  /**操作人员信息 */
  const [personModalVisible, setPersonModalVisible] = useState(false);
  const [formPerson] = Form.useForm();
  const [readyEditPerson, setReadyEditPerson] = useState(null); // 待编辑的人员

  const showPersonModal = (record = null) => {
    setPersonModalVisible(true);
    if (record) {
      formPerson.setFieldsValue(record);
    } else {
      formPerson.resetFields();
    }
  };

  const handlePersonModalOk = () => {
    formPerson
      .validateFields()
      .then(async values => {
        const { groupId = currentGroupId, id } = readyEditPerson ?? {};
        const params = {
          groupId,
          id,
          ...values,
          birth: moment(values.birth).format(timeFormat),
        };
        const json = jsonDoEncrypt(params);
        const { response, error } = await flatTryCatch(industryIpaApi.createPerson({ json }));
        if (error) return;
        if (response.code === 0) {
          fetchDataList(
            { groupId: currentGroupId, ...formSearch.getFieldsValue() },
            pagination.current,
            pagination.pageSize
          );
        }
        setPersonModalVisible(false);
      })
      .catch(info => {
        console.log('Validate Failed:', info);
      });
  };

  const handlePersonModalCancel = () => {
    setPersonModalVisible(false);
  };

  const handleAddPerson = () => {
    setReadyEditPerson(null);
    showPersonModal();
  };

  const handleEditPerson = record => {
    const { groupId, id, birth, ...remain } = record;

    setReadyEditPerson({ groupId, id });
    showPersonModal({ ...remain, birth: birth ? moment(birth, timeFormat) : undefined });
  };

  const handleDeletePerson = record => {
    const { name, id } = record;
    Modal.confirm({
      title: '删除通讯录',
      icon: <DeleteOutlined />,
      content: `确定删除通讯录【${name}】吗, 是否继续?`,
      async onOk() {
        const { response, error } = await flatTryCatch(industryIpaApi.deletePerson({ id }));
        if (error) return;
        if (response.code === 0) {
          message.success('删除成功');
          fetchDataList(
            { groupId: currentGroupId, ...formSearch.getFieldsValue() },
            pagination.current,
            pagination.pageSize
          );
        }
      },
      onCancel() {
        console.log('Delete cancelled');
      },
    });
  };

  /**人员列表 */
  const [formSearch] = Form.useForm();
  const [tableDataList, setTableDataList] = useState([]);
  const [tableLoading, setTableLoading] = useState<boolean>(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total: number) => `共${total}条`,
  });
  const columns: ColumnsType = [
    {
      title: '序号',
      render: (text, record, index) => index + 1 + pagination.pageSize * (pagination.current - 1),
      width: 100,
    },
    ...invariableCol,
    {
      title: '操作',
      key: 'action',
      render: (_, record: any) => (
        <div>
          <Button type="link" onClick={() => handleEditPerson(record)}>
            编辑
          </Button>
          <Button type="link" danger onClick={() => handleDeletePerson(record)}>
            删除
          </Button>
        </div>
      ),
    },
  ];

  // 获取通讯录人员数据
  const fetchDataList = useCallback(async (values: any, page: number, limit: number) => {
    setTableLoading(true);
    const params = { page, limit, ...values };

    const { response, error } = await flatTryCatch(industryIpaApi.readPerson(params));
    setTableLoading(false);
    if (error) return;

    const { totalCount = 0, list = [], currPage = 1, pageSize = 10 } = response.data ?? {};
    setTableDataList(list);
    setPagination({
      current: currPage,
      pageSize,
      total: totalCount,
      showTotal: (total: number) => `共${total}条`,
    });
  }, []);

  useEffect(() => {
    fetchDataList({}, 1, 10);
  }, [fetchDataList]);

  // 操作: 搜索
  const handleFinish = debounce((values: any) => {
    fetchDataList({ groupId: currentGroupId, ...values }, 1, pagination.pageSize);
  }, 500);

  // 操作: 重置
  const handleReset = debounce(() => {
    formSearch.resetFields();
    fetchDataList({ groupId: currentGroupId }, 1, 10);
  }, 500);

  // 操作: 页码改变
  const handleTableChange = newPagination => {
    setPagination(newPagination);
    fetchDataList(
      { groupId: currentGroupId, ...formSearch.getFieldsValue() },
      newPagination.current,
      newPagination.pageSize
    );
  };

  // 批量删除
  const [selectedRowKeys, setSelectedRowKeys] = useState([]);
  const rowSelection = {
    selectedRowKeys,
    onChange: selectedKeys => {
      setSelectedRowKeys(selectedKeys);
    },
  };
  const handleBatchDelete = () => {
    // 确认对话框
    Modal.confirm({
      title: '删除通讯录',
      icon: <DeleteOutlined />,
      content: `确定要删除选中的 ${selectedRowKeys.length} 条通讯录数据吗？`,
      onOk: async () => {
        const { response, error } = await flatTryCatch(
          industryIpaApi.deletePerson({ idList: selectedRowKeys })
        );
        if (error) return;
        if (response.code === 0) {
          setSelectedRowKeys([]);
          message.success('删除成功');
          fetchDataList(
            { groupId: currentGroupId, ...formSearch.getFieldsValue() },
            pagination.current,
            pagination.pageSize
          );
        }
      },
    });
  };

  /** 文件上传 */
  const [uploadLoading, setUploadLoading] = useState(false);
  const beforeUpload = file => {
    const allowedExtensions = ['.xls', '.xlsx', '.csv', '.et'];
    const fileName = file.name.toLowerCase();
    const isValid = allowedExtensions.some(ext => fileName.endsWith(ext));

    if (!isValid) {
      message.error('仅支持上传 xls、xlsx、csv 或 et 格式的文件');
      return Upload.LIST_IGNORE;
    }
  };

  const handleUpload: any = ({ file, onSuccess, onError }) => {
    const formData = new FormData();
    formData.append('file', file);
    formData.append('groupId', currentGroupId);

    setUploadLoading(true);
    const encryptToken = (store.getState() as JSONObject).encryptToken;
    // process.env.REACT_APP_API_URL +
    fetch('/weathersms/web/industry/sysContactGroup/import', {
      method: 'POST',
      body: formData,
      headers: { encryptToken },
    })
      .then(response => response.json())
      .then(({ code, msg }) => {
        if (code === 0) {
          message.success('通讯录导入成功');
          onSuccess('ok');
          fetchDataList(
            { groupId: currentGroupId, ...formSearch.getFieldsValue() },
            pagination.current,
            pagination.pageSize
          );
        } else {
          Modal.error({
            title: '通讯录导入失败',
            content: msg,
            closable: true,
            className: 'error-popup', // 这个css为了改变antd内部自己的元素
          });
          onError('通讯录导入失败');
        }
      })
      .catch(error => {
        message.error('通讯录导入失败');
        onError('通讯录导入失败');
      })
      .finally(() => {
        setUploadLoading(false);
      });
  };

  /** 文件导出 */
  const [exportLoading, setExceptLoading] = useState(false);
  const handleExportPerson = () => {
    // 发起请求，获取文件
    setExceptLoading(true);
    // process.env.REACT_APP_API_URL +
    fetch('/weathersms/web/industry/sysContactGroup/export?groupId=' + currentGroupId, {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        encryptToken: (store.getState() as JSONObject).encryptToken,
      },
    })
      .then(response => {
        if (!response.ok) {
          throw new Error('Network response was not ok');
        }
        return response.blob(); // 将响应体转换为Blob对象
      })
      .then(blob => {
        // 创建一个链接元素，用于下载文件
        const url = window.URL.createObjectURL(blob);
        const a = document.createElement('a');
        a.href = url;
        a.download = '通讯录.xlsx'; // 设置下载文件的名称
        document.body.appendChild(a);
        a.click();
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url); // 释放对象URL
        message.success('通讯录导出成功');
      })
      .catch(error => {
        console.error('There has been a problem with your fetch operation:', error);
        message.error('通讯录导出失败');
      })
      .finally(() => {
        setExceptLoading(false);
      });
  };

  return (
    <div className="ipa-wrapper" aria-hidden="true">
      <div className="ipa-group">
        <div className="group-headline">
          <div className="group-title">通讯录分组</div>
          <Button
            type="primary"
            icon={<PlusOutlined />}
            size="small"
            onClick={handleAddTree}
          ></Button>
        </div>
        <div className="group-tree">
          <Tree
            blockNode
            defaultSelectedKeys={['root']}
            defaultExpandedKeys={['root']}
            fieldNames={{ title: 'name', key: 'id', children: 'children' }}
            titleRender={renderTitle}
            onSelect={handleSelectTree}
            treeData={treeData}
          />
        </div>
      </div>
      <div className="ipa-person">
        <Form layout="inline" form={formSearch} onFinish={handleFinish} className="m20">
          <Form.Item label="姓名" name="name">
            <Input placeholder="请输入姓名" style={{ width: 140 }} />
          </Form.Item>
          <Form.Item label="手机号码" name="phone">
            <Input placeholder="请输入手机号码" style={{ width: 140 }} />
          </Form.Item>
          <Form.Item>
            <Button type="primary" htmlType="submit">
              搜索
            </Button>
            <Button style={{ marginLeft: 8 }} onClick={handleReset}>
              重置
            </Button>
          </Form.Item>
        </Form>
        <Space className="m16">
          <Button type="primary" disabled={!currentGroupId} onClick={handleAddPerson}>
            新增
          </Button>
          <Upload
            customRequest={handleUpload}
            beforeUpload={beforeUpload}
            fileList={[]}
            accept=".xls,.xlsx,.csv,.et"
          >
            <Button type="primary" loading={uploadLoading} disabled={!currentGroupId}>
              导入
            </Button>
          </Upload>
          <FileDownload fileContent={fileContent} />
          <Button
            type="primary"
            loading={exportLoading}
            disabled={!currentGroupId || !tableDataList.length}
            onClick={handleExportPerson}
          >
            导出
          </Button>
          <Button danger disabled={selectedRowKeys.length === 0} onClick={handleBatchDelete}>
            批量删除
          </Button>
        </Space>
        <Table
          rowSelection={rowSelection}
          loading={tableLoading}
          dataSource={tableDataList}
          columns={columns}
          rowKey="id"
          pagination={pagination}
          onChange={handleTableChange}
          scroll={{ x: 'max-content', y: window.innerHeight - 390 }}
        />
      </div>

      <Modal
        title={readyEditTree ? '修改通讯录分组' : '创建通讯录分组'}
        visible={treeModalVisible}
        onOk={handleTreeModalOk}
        onCancel={handleTreeModalCancel}
      >
        <Form form={formTree} name="name" onFinish={handleTreeModalOk}>
          <Form.Item
            name="name"
            label="分组名称"
            rules={[{ required: true, message: '请输入分组名称' }]}
          >
            <Input placeholder="请输入分组名称" maxLength={10} />
          </Form.Item>
        </Form>
      </Modal>

      <Modal
        title={readyEditPerson ? '修改通讯录' : '创建通讯录'}
        visible={personModalVisible}
        onOk={handlePersonModalOk}
        onCancel={handlePersonModalCancel}
      >
        <Form form={formPerson} name="name" onFinish={handlePersonModalOk}>
          <Form.Item
            name="name"
            label="联系人名称"
            rules={[{ required: true, message: '请输入联系人名称' }]}
          >
            <Input placeholder="请输入联系人名称" />
          </Form.Item>
          <Form.Item
            name="phone"
            label="联系人号码"
            rules={[
              { required: true, message: '请输入联系人号码' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '请输入有效的手机号',
              },
            ]}
          >
            <Input placeholder="请输入联系人号码" />
          </Form.Item>
          <Form.Item
            name="email"
            label="联系人邮箱"
            rules={[
              {
                pattern: /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,6}$/,
                message: '请输入有效的邮箱',
              },
            ]}
          >
            <Input placeholder="请输入联系人邮箱" />
          </Form.Item>
          <Form.Item name="birth" label="联系人生日">
            <DatePicker showToday={false} placeholder="请选择日期" />
          </Form.Item>
          <Form.Item name="gender" label="联系人性别">
            <Radio.Group>
              <Radio value={'0'}>男</Radio>
              <Radio value={'1'}>女</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item name="remark" label="备注">
            <TextArea rows={4} placeholder="请输入备注" />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};

export default AddressBook;
